package com.mingle.iwalk;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlpull.v1.XmlSerializer;

import com.mingle.iwalk.uploader.Status;
import com.mingle.iwalk.uploader.iWalk;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Xml;

public class Utils
{
	static public List<Location> parseTrackPath(String path) throws Exception
	{
		if(path==null || path.length()==0)
		{
			return null;
		}
		
		List<Location> locList = new ArrayList<Location>();
		
		 FileInputStream fileIS = new FileInputStream(path);
  
		 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		 DocumentBuilder db = dbf.newDocumentBuilder();
		 Document doc = db.parse(fileIS);
		
		 doc.getDocumentElement().normalize();
		 NodeList nodeList = doc.getElementsByTagName("Location");
		 for(int i = 0; i < nodeList.getLength(); i++)
		 {
			Node locNode = nodeList.item(i);
			Node latNode = locNode.getFirstChild();
			Node lonNode = latNode.getNextSibling();
			Node altNode = lonNode.getNextSibling();
			Node accNode = altNode.getNextSibling();
			Node timeNode = accNode.getNextSibling();
			
			/*double lat = Double.valueOf(latNode..getTextContent());
			double lon = Double.valueOf(lonNode.getTextContent());
			double alt = Double.valueOf(altNode.getTextContent());
			double acc = Double.valueOf(accNode.getTextContent());
			long time = Long.valueOf(timeNode.getTextContent());*/
			
			double lat = Double.valueOf(latNode.getFirstChild().getNodeValue());
			double lon = Double.valueOf(lonNode.getFirstChild().getNodeValue());
			double alt = Double.valueOf(altNode.getFirstChild().getNodeValue());
			double acc = Double.valueOf(accNode.getFirstChild().getNodeValue());
			long time = Long.valueOf(timeNode.getFirstChild().getNodeValue());
			
			Location loc = new Location(LocationManager.GPS_PROVIDER);
			loc.setLatitude(lat);
        	loc.setLongitude(lon);
        	loc.setAltitude(alt);
        	loc.setAccuracy((float) acc);
        	loc.setTime(time);
        	locList.add(loc);
		 }
		
		 return locList;
	}

	public static void createTrackFile(String path, List<Location> locList)
	{
		File f = new File(path);
		if(!f.exists())
		{
			try {
				f.createNewFile();
			} catch (IOException e) {
				
				e.printStackTrace();
			}
		}

		FileOutputStream outputStream;
		try {
			outputStream = new FileOutputStream(f);
			OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
			XmlSerializer serializer = Xml.newSerializer();
			serializer.setOutput(writer);
			serializer.setOutput(outputStream, "utf-8");
			serializer.startDocument("utf-8", true);
			serializer.startTag(null, "Locations");
			serializer.attribute(null, "count", String.valueOf(locList.size()));

			for (Location location : locList) {
				serializer.startTag(null, "Location");

				serializer.startTag(null, "lat");
				serializer.text(String.valueOf(location.getLatitude()));
				serializer.endTag(null, "lat");
				
				serializer.startTag(null, "lon");
				serializer.text(String.valueOf(location.getLongitude()));
				serializer.endTag(null, "lon");
	          
				serializer.startTag(null, "alt");
				serializer.text(String.valueOf(location.getAltitude()));
				serializer.endTag(null, "alt");
				
				serializer.startTag(null, "acc");
				serializer.text(String.valueOf(location.getAccuracy()));
				serializer.endTag(null, "acc");
				
				serializer.startTag(null, "time");
				serializer.text(String.valueOf(location.getTime()));
				serializer.endTag(null, "time");
				
				serializer.endTag(null, "Location");
			}

			serializer.endTag(null, "Locations");
			serializer.endDocument();
			outputStream.close();
			
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			
			e.printStackTrace();
		} catch (IllegalStateException e) {
			
			e.printStackTrace();
		} catch (IOException e) {
			
			e.printStackTrace();
		}

	}
	
	public static Bitmap bitmapResize(String path)
	{
		Bitmap bitmap = BitmapFactory.decodeFile(path);
    	int w = bitmap.getWidth();
    	int h = bitmap.getHeight();
    	int frameWidth =300;
    	int frameHeight =200;
    	
    	Matrix matrix = new Matrix();
    	
    	if(frameWidth * h > frameHeight * w)
    	{
    		float scaleX =(float) ((float)frameWidth /(double)w);
	    	float scaleY = scaleX;
	    	matrix.postScale(scaleX, scaleY);
    	}
    	else
    	{
    		float scaleY =(float) ((float)frameHeight /(double)h);
    		float scaleX = scaleY;
	    	
	    	matrix.postScale(scaleX, scaleY);
    	}

    	Bitmap resizeBitmap = Bitmap.createBitmap(bitmap,0,0, w, h, matrix, false);
    	bitmap.recycle();
    	
    	return resizeBitmap;
	}
	
	public static  boolean detectNetwork(Context context) {  
        
	       ConnectivityManager manager = (ConnectivityManager) context.getSystemService(  
	                     Context.CONNECTIVITY_SERVICE);  
	        
	       if (manager == null) {  
	           return false;  
	       }  
	        
	       NetworkInfo networkinfo = manager.getActiveNetworkInfo();  
	        
	       if (networkinfo == null || !networkinfo.isAvailable()) {  
	           return false;  
	       }  
	   
	       return true;  
	} 
	
	public static int uploadTravelInfo(TravelerInfo info, int type)
	{
		if(type == TravelerInfo.INFO_TYPE_POI)
		{
			iWalk walk = new iWalk();
			walk.setUserid("idiot727");
			walk.setUserpass("1985226");
			Status status = walk.updateStatus(info.title, info.description, info.id);
			
			return status.getHttpResposeCode();
		}
		else if(type == TravelerInfo.INFO_TYPE_TRACK)
		{
			iWalk walk = new iWalk();
			walk.setUserid("idiot727");
			walk.setUserpass("1985226");
			Status status = walk.updateStatus(info.title, info.description, info.id);
			return status.getHttpResposeCode();
		}
		
		return -1;
	}

}
